package com.bnq.rnmodule.rnupdater;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.bnq.rnmodule.rnupdater.downApkDialog;
/**
 * Created by user on 16/6/14.
 */
public class downApkAndInstall {
    public static final int DOWN_ERROR = 0x00003;
    public static Handler mHandler;

    public static void start(boolean isFouce, final String url, final Activity activity) {

        final downApkDialog apkDownloadDialog;
        apkDownloadDialog = new downApkDialog(activity);
        apkDownloadDialog.setCancelable(!isFouce);
        apkDownloadDialog.show();
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub

                super.handleMessage(msg);
                switch (msg.what) {
                    case DOWN_ERROR:
                        apkDownloadDialog.dismiss();
                        Toast.makeText(activity.getApplicationContext(), activity.getApplicationContext().getString(R.string.getnewversionfailed), Toast.LENGTH_LONG).show();

                        break;
                }
            }
        };
        new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();

                    Log.d("SJQ", "run");
                    File file = getFileFromServer(url, apkDownloadDialog,
                            activity.getDir("tmp", Context.MODE_PRIVATE));
                    sleep(3000);
                    Log.d("SJQ", "before installApk");
                    installApk(file, activity);
                    apkDownloadDialog.dismiss();
                    Looper.loop();
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    mHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static void installApk(File file, Activity activity) {

        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        activity.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static File getFileFromServer(String path, downApkDialog pd, File fileCatch) throws Exception {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            pd.setMax(conn.getContentLength());

            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(fileCatch, "/updata.apk");
            String[] command = {"chmod", "777", file.getPath()};
            ProcessBuilder builder = new ProcessBuilder(command);
            try {
                builder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
    }
}
